//
//  AdvancedListController.m
//  MClient
//
//  Created by  wangfei on 10-3-31.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CustomAListController.h"
#import "MClientAppDelegate.h"
#import "MServerDAO.h"
#import "MCFunction.h"
#import "QueryController.h"
#import "MCUIToolkit.h"
#import "WithFormButtonsBar.h"

@interface CustomAListController (Private)
//CGPoint startPoint;
//int actionSheetFlag;
@end

@implementation CustomAListController
@synthesize dataObjectName;
@synthesize layoutName;
@synthesize queryFilter;
@synthesize page;
@synthesize listData;
@synthesize listLayout;
@synthesize otherParams;

// 初始化view
- (void)viewDidLoad {
	
	[super viewDidLoad];
	cellWidth = self.width;
	cellHeight = 0.0;
	imageWidth = 0.0;
	imageHeight = 0.0;
	imagesCache = [[NSMutableDictionary alloc] init];
	
	[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	
	pageBar = [MCUIToolkit getPageBar:[MCUIToolkit hasQueryField:listLayout] delegate:self];
	pageBar.frame = CGRectMake(0, self.height-nToolBarHeight, self.width, nToolBarHeight);
	pageBar.autoresizingMask = nMCViewAutoresizingMask;
	[self.clientView addSubview:pageBar];
	
	self.tableview.backgroundColor = [UIColor clearColor];
	self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableview.frame = CGRectMake(0, 0, self.width, self.height-pageBar.frame.size.height);
	buttonCol = 1;
	if ([listLayout objectForKey:@"csty"]) {
		if ([[listLayout objectForKey:@"csty"] objectForKey:@"button_col"]) {
			buttonCol =  [[[listLayout objectForKey:@"csty"] objectForKey:@"button_col"] intValue];
			if (buttonCol > 3) {
				buttonCol = 3;
			}
		}
	}
	// 根据配置显示/隐藏帮助按钮
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter04.html";
	aListInfo = [[NSMutableDictionary alloc] init];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	//int nHeight = CGRectGetHeight(pageBar.frame);
	//tableview.frame = CGRectMake(0, 0, self.width, self.height-nHeight);
	//pageBar.frame = CGRectMake(0, self.height-nHeight, self.width, nHeight);
}

- (void)dealloc {
	[pageBar release];
	[dataObjectName release];
	[layoutName release];
	[queryFilter release];
	[listData release];
	[listLayout release];
	[listButtons release];
	[listDescButtons release];
	[aListInfo release];
	[withFormButtons release];
	[imagesCache release];
	[otherParams release];
    [super dealloc];
}

#pragma mark ---UIToolbar事件---
-(void)goFirst:(id)inSender {
	if (page != 1) {
		page = 1;
		[self getDataFromServer];
	}
	
}

-(void)goPrevious:(id)inSender {
	if (page > 1) {
		page = page - 1;
		[self getDataFromServer];
	}
}

-(void)goNext:(id)inSender {
	if (page < totalPage) {
		page = page + 1;
		[self getDataFromServer];
	}
}

-(void)goLast:(id)inSender {
	if (page != totalPage) {
		page = totalPage;
		[self getDataFromServer];
	}
}

-(void)gotoPage:(id)inSender {
	UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
	int goPage = [inputView.text intValue];
	if (goPage >= 1 && goPage <= totalPage) {
		page = goPage;
		[self getDataFromServer];
	}
}

-(void)reload:(id)inSender {
	[self getDataFromServer];
}

-(void)search:(id)inSender {
	
	QueryController *queryController = [[QueryController alloc] initWithStyle:UITableViewStylePlain];
	queryController.listLayout = self.listLayout;
	queryController.queryFilter = self.queryFilter;
	queryController.queryFirst = NO;
	[self.navigationController pushViewController:queryController animated:YES];
	[queryController release];
}

#pragma mark ---- 数据加载方法 ----
- (void)getDataFromServer {	
	[(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1] resignFirstResponder];
	[imagesCache removeAllObjects];
	[[MServerDAO sharedInstance] getCustomListAsync:layoutName
										queryFilter:queryFilter
											   page:[NSString stringWithFormat:@"%d", page]
										otherParams:otherParams
										   delegate:self];		
}

- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	self.listLayout = returnValue;
	listData = [[NSMutableDictionary alloc] init];
	
	NSMutableArray *recordList = [NSMutableArray array];
	if ([listLayout objectForKey:@"rl"]) {
		recordList = [listLayout objectForKey:@"rl"];
	}
	[self.listData setObject:recordList forKey:@"rl"];
	
	listButtons = [[NSMutableArray alloc] init];
	if ([listLayout objectForKey:@"btn"]) {
		listButtons = [[listLayout objectForKey:@"btn"] retain];
	}
	[self.listData setObject:listButtons forKey:@"btn"];
	
	totalPage = 1;
	if ([self.listLayout objectForKey:@"tp"]) {
		totalPage = [[self.listLayout objectForKey:@"tp"] intValue];
	}
	if (totalPage == 0) {
		totalPage = 1;
	}
	if ([pageBar.items count] > 5) {
		UITextField *inputView = (UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:1];
		inputView.text = @"";
		inputView.placeholder = [NSString stringWithFormat:@"%d", page];
		UILabel *pageLabel = (UILabel *)(UITextField *)[((UIBarButtonItem *)[pageBar.items objectAtIndex:4]).customView viewWithTag:2];
		pageLabel.text = [NSString stringWithFormat:@"/%d", totalPage];
	}
	self.title = [listLayout objectForKey:@"lbl"];
	withFormButtons = [MCUIToolkit getWithFormButtons:listButtons];
	int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
	if (withFormButtonsBarHeight != 0) {
		WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, withFormButtonsBarHeight)];
		withFormButtonsBar.tag = -8888;
		[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
		self.tableview.tableFooterView = withFormButtonsBar;
		[withFormButtonsBar release];
	}
	
	[self rightBarButton:@"操作" withStyle:UIBarButtonItemStyleDone selector:@selector(selectAction:)];
	if ([listButtons count] == 1) {
		self.rightBarButtonItemTitle = [[listButtons objectAtIndex:0] objectForKey:@"lbl"];
	} else if ([listButtons count] > 1) {
		self.rightBarButtonItemTitle = @"操作";
	} else {
		self.rightBarButtonItem = nil;
	}
	
	//动态表单标签
	if ([returnValue objectForKey:@"csty"]) {
		NSMutableDictionary *csty = [returnValue objectForKey:@"csty"];
		if ([csty objectForKey:@"label"]) {
			self.title = [csty objectForKey:@"label"];
		}
	}
	
	NSMutableArray *listFields = [listLayout objectForKey:@"item"];
	if ([[self.listData objectForKey:@"rl"] count] > 0) {
		NSMutableDictionary *record = [[self.listData objectForKey:@"rl"] objectAtIndex:0];
		for (int i = 0; i < [listFields count]; i++) {
			NSMutableDictionary *appItem = [listFields objectAtIndex:i];
			if ([[appItem objectForKey:@"v"] boolValue]) {
				NSString *fieldType = [MCUIToolkit getFieldType:appItem];
				NSString *fieldName = [MCUIToolkit getFieldName:appItem];
				NSMutableDictionary *fieldData = [[record objectForKey:@"data"] objectForKey:fieldName];
				if ([fieldType isEqualToString:@"S"]) {
					imageWidth = nImageWidthOfCell;
					imageHeight = nImageHeightOfCell;
					NSMutableDictionary *style = [fieldData objectForKey:@"style"];
					if (nil != style) {
						if ([style objectForKey:@"width"]) {
							imageWidth = [[style objectForKey:@"width"] floatValue];
						}
						if ([style objectForKey:@"height"]) {
							imageHeight = [[style objectForKey:@"height"] floatValue];
						}
					}
					if (imageWidth > self.width) {
						imageHeight = self.width * imageHeight / imageWidth;
						imageWidth = self.width;
					}
					cellWidth = self.width - imageWidth;
				}
			}
		}
	}	
	[self.tableview reloadData];		
}


#pragma mark ---- UITableView处理方法 ----

//TableView的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSMutableArray *recordList = [self.listData objectForKey:@"rl"];
	return [recordList count];	
}

//每一行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	int row = [indexPath row];
	
	NSMutableArray *cellInfos = [MCUIToolkit getAListInfo:listLayout
												 listData:[self.listData objectForKey:@"rl"]
												 rowIndex:row
												cellWidth:cellWidth];
	[aListInfo setObject:cellInfos forKey:[NSNumber numberWithInt:row]];
	if ([cellInfos count] <= 0) {
		return 0.0;
	}
	cellHeight = [[[cellInfos objectAtIndex:([cellInfos count] - 1)] objectForKey:@"cellHeight"] floatValue];
	if (cellHeight < imageHeight) {
		cellHeight = imageHeight + 12.0;
		return cellHeight;
	}
	if (cellHeight == 0.0) {
		return cellHeight;
	}
	if (cellHeight < 28.0) {
		return 44.0;
	}
	return cellHeight + 6.0;
}

//初始化TableVie根据参数和数据绘制每一行以及填充数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
	UITableViewCell *cell = [MCUIToolkit getAListCell:[aListInfo objectForKey:[NSNumber numberWithInt:row]]
										  imagesCache:imagesCache
											 rowIndex:row
										isMultiSelect:NO
											cellWidth:cellWidth
										   cellHeight:cellHeight
										   imageWidth:imageWidth
										  imageHeight:imageHeight];
	return cell;	
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	int row = [indexPath row];
	actionSheetFlag = row;
	
	NSMutableDictionary *record = [[self.listData objectForKey:@"rl"]objectAtIndex:row];	
	
	listDescButtons = [[record objectForKey:@"btn"] retain];
	
	if ([listDescButtons count] <= 0) {
		return;
	}
	if ([listDescButtons count] == 1) {
		NSString *pKey = @"";
		if ([record objectForKey:@"key"] != nil) {
			pKey = [record objectForKey:@"key"];
		}
		NSMutableDictionary *button = [listDescButtons objectAtIndex:0];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"list_rec",@"buttonType",
										   self.dataObjectName,@"dataObjectName",
										   record,@"formData",
										   pKey, @"primaryKey", nil];
		
		if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:[button objectForKey:@"cfmi"] 
					   naviController:self.navigationController];
		}else{
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] parameters:parameters confirmMessage:nil naviController:self.navigationController];
			
		}
		[parameters release];
	} else if ([listDescButtons count] > 1) {
		actionSheetFlag = row;
		UIActionSheet *menu = [MCUIToolkit actionSheet:listDescButtons
											   withTag:0
										  withDelegate:self
											 withTitle:@"请选择明细操作"];
		[menu showInView:self.clientView.window];
	}	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)withFormButtonsAction:(id) sender {
	NSMutableDictionary *button = [withFormButtons objectAtIndex:((UIButton *)sender).tag];
	if ([MCErrorManagement showAuthMessage:button]) {
		return;
	}
	NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
	NSMutableDictionary *url = [button objectForKey:@"url"];
	NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
									   buttonId,@"buttonId",
									   @"list_form",@"buttonType",
									   self.dataObjectName,@"dataObjectName",nil];
	if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
		[MCFunction pushViewByUrl:url	
					   parameters:parameters
				   confirmMessage:[button objectForKey:@"cfmi"] 
				   naviController:self.navigationController];
	}else {
		[MCFunction pushViewByUrl:url	
					   parameters:parameters
				   confirmMessage:nil 
				   naviController:self.navigationController];
	}
	[parameters release];	
}

//导航栏上动作按钮的点击事件
- (void) selectAction: (id) sender {
	if ([listButtons count] == 1) {
		NSMutableDictionary *button = [listButtons objectAtIndex:0];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		
		NSMutableDictionary *url = [button objectForKey:@"url"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"list_form",@"buttonType",
										   self.dataObjectName,@"dataObjectName",nil];
		if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
			[MCFunction pushViewByUrl:url	
						   parameters:parameters
					   confirmMessage:[button objectForKey:@"cfmi"] naviController:self.navigationController];
		}else {
			[MCFunction pushViewByUrl:url	
						   parameters:parameters
					   confirmMessage:nil naviController:self.navigationController];
		}
		[parameters release];
		return;
	}	
	
	actionSheetFlag = -1;
	UIActionSheet *menu = [MCUIToolkit actionSheet:listButtons
										   withTag:0
									  withDelegate:self
										 withTitle:@"选择操作"];
	[menu showFromTabBar:(UITabBar *)[self.navigationController view]];
}


//弹出菜单按钮点击事件，当actionSheetFlag等于-1的时候执行列表动作，否则执行列表明细动作
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	if (actionSheetFlag == -1) {
		if (buttonIndex == [listButtons count]) {
			// 按下取消按钮
			return;
		}
		NSMutableDictionary *button = [listButtons objectAtIndex:buttonIndex];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		NSMutableDictionary *url = [button objectForKey:@"url"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"list_form",@"buttonType",
										   self.dataObjectName,@"dataObjectName",nil];
		if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
			[MCFunction pushViewByUrl:url	
						   parameters:parameters
					   confirmMessage:[button objectForKey:@"cfmi"] naviController:self.navigationController];
		}else {
			[MCFunction pushViewByUrl:url	
						   parameters:parameters
					   confirmMessage:nil naviController:self.navigationController];
		}
		[parameters release];
	}
	else {
		if (buttonIndex == [listDescButtons count]) {
			// 按下取消按钮
			return;
		}
		NSMutableDictionary *record = [[self.listData objectForKey:@"rl"]objectAtIndex:actionSheetFlag];
		
		NSMutableDictionary *button = [listDescButtons objectAtIndex:buttonIndex];
		if ([MCErrorManagement showAuthMessage:button]) {
			return;
		}
		NSString *pKey = @"";
		if ([record objectForKey:@"key"] != nil) {
			pKey = [record objectForKey:@"key"];
		}
		NSString *buttonId = [button objectForKey:@"id"] == nil?@"":[button objectForKey:@"id"];
		NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										   buttonId,@"buttonId",
										   @"list_rec",@"buttonType",
										   self.dataObjectName,@"dataObjectName",
										   record,@"formData",
										   pKey, @"primaryKey", nil];
		
		if ([button objectForKey:@"cfmi"] != nil && ![@"" isEqualToString:[button objectForKey:@"cfmi"]]){
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:[button objectForKey:@"cfmi"] 
					   naviController:self.navigationController];
		}else{
			[MCFunction pushViewByUrl:[button objectForKey:@"url"] 
						   parameters:parameters 
					   confirmMessage:nil 
					   naviController:self.navigationController];
		}
		[parameters release];
	}
}

- (void) selectCancelAction: (id) sender {
	UIViewController *viewController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
	if ([viewController isMemberOfClass:[QueryController class]]){
		[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 3] animated:YES];
		return;
	}
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	int withFormButtonsBarHeight = [MCUIToolkit getWithFormButtonsBarHeight:withFormButtons buttonCol:buttonCol];
	if (withFormButtonsBarHeight != 0) {
		WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, withFormButtonsBarHeight)];
		withFormButtonsBar.tag = -8888;
		[withFormButtonsBar addWithFormButtons:withFormButtons buttonCol:buttonCol delegate:self];
		self.tableview.tableFooterView = withFormButtonsBar;
		[withFormButtonsBar release];
	}
}

@end
